package com.bird.pro.interceptor;

import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.bird.pro.annotation.Auth;
import com.bird.pro.config.WechatConfig;
import com.bird.pro.pojo.BirdUser;
import com.bird.pro.service.IUserService;
import com.bird.pro.utils.CommonUtil;
import com.bird.pro.utils.Token;
import com.bird.pro.utils.WeChatInfo;
import com.bird.pro.utils.WeixinUserInfo;
import com.bird.pro.wechat.WechatBase;
import com.vdurmont.emoji.EmojiParser;

@Component
public class AuthInterceptor implements HandlerInterceptor {
	@Autowired
	private IUserService userService;

	private static final Logger log = LoggerFactory.getLogger(AuthInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		HandlerMethod hm = (HandlerMethod) handler;
		String authScope = "";

		Auth auth = null;
		// 首先检查方法上的注解
		auth = hm.getMethodAnnotation(Auth.class);
		if (auth != null) {
			authScope = auth.scope().toString();
		} else {
			// 再检查类上的注解
			auth = hm.getClass().getAnnotation(Auth.class);
			if (auth != null) {
				authScope = auth.scope().toString();
			}
		}
		if (StringUtils.isNotBlank(authScope)) {
			HttpSession session = request.getSession();
			if (session.getAttribute("wechatUser") == null) {
				String code = request.getParameter("code");
				if (StringUtils.isNotBlank(code)) {
					WechatBase wb = new WechatBase();
					// 解析
					if ("snsapi_base".equals(authScope)) {
						// 获取用户的openid
						String openId = WeChatInfo.getOpenID(code);
						wb.setOpenId(session, openId);
					} else {
						Token token = CommonUtil.getToken(WechatConfig.appId, WechatConfig.appSecret, code);
						String accessToken = token.getAccessToken();
						String openId = token.getOpenId();
						WeixinUserInfo chat = WeChatInfo.getUserInfo(accessToken, openId);
						BirdUser user = userService.getUserByOpenId(openId);
						if (user == null) {
							user = new BirdUser();
							user.setCreateTime(new Date());
							user.setOpenId(chat.getOpenId());
							// 移除特殊表情
							user.setUserName(EmojiParser.removeAllEmojis(chat.getNickname()));
							user.setUserProvince(chat.getProvince());
							user.setUserCity(chat.getCity());
							user.setUserCounty(chat.getCountry());
							user.setUserState("1");
							int result = userService.saveUser(user);
							user.setId(result);
						}
						wb.setOpenId(session, openId);
						wb.setUserInfo(session, user);

					}
					return true;
				}
				// 跳转授权
				StringBuffer url = request.getRequestURL();
				StringBuffer urlParams = new StringBuffer();
				Map<String, String[]> params = request.getParameterMap();

				for (String urlParam : params.keySet()) {
					// 这里要过滤下code
					if (!"code".equals(urlParam)) {
						continue;
					}
					urlParams.append("&").append(urlParam);
					urlParams.append("=").append(params.get(urlParam));
				}
				url.append("?").append(params.size() > 0 ? urlParams.substring(1) : urlParams);
				response.sendRedirect(CommonUtil.getAuthUrl(url.toString(), authScope));
				return false;
			}
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		log.info("--------------处理请求完成后视图渲染之前的处理操作---------------");
		HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		log.info("---------------视图渲染之后的操作-------------------------0");
		HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
	}

}
